package cate.game.role.mail;

import cate.common.table.d.GDOperation;
import cate.game.mail.po.MailBuilder;
import cate.game.res.MixRes;
import cate.game.role.Role;
import com.fasterxml.jackson.annotation.JsonIgnore;
import cp.solution.business.gm.GmMailEntity;
import easy.java.dev.note.NoteField;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.annotation.Transient;

import java.util.Iterator;
import java.util.List;

@Slf4j
public class RoleGmMail {

    @NoteField(value = "邮件执行ID")
    public int exeId;

    @Transient
    @JsonIgnore
    private transient RoleMail roleMail;

    public void initialize(RoleMail roleMail) {
        this.roleMail = roleMail;
        log.info("当前GM邮件exeId={}", exeId);
    }

    private static boolean matchRole(Role role, GmMailEntity m) {
        if(!m.matchLevel(role.getBase().level)) {
            return false;
        }
        if(!m.matchSrvId(role.getBase().srvId)) {
            return false;
        }
        if(StringUtils.isNotBlank(m.getGroupCode())) {
            if(!StringUtils.equals(m.getGroupCode(), role.getGame().config.gs.getGroupCode())) {
                return false;
            }
        }
        if(StringUtils.isNotBlank(m.getGameId())) {
            if(!StringUtils.equals(m.getGameId(), role.getBase().gameId)) {
                return false;
            }
        }
        if(!m.matchRoleId(role.getUid())) {
            return false;
        }
        return true;
    }

    public void scan(List<GmMailEntity> mailList) {
        try {
            Iterator<GmMailEntity> iter = mailList.iterator();
            while (iter.hasNext()) {
                GmMailEntity m = iter.next();
                if (m.getExeId() > this.exeId && matchRole(roleMail.getRole(), m)) {
                    Mail mail = new MailBuilder()
                            .setTitle(m.getTitle())
                            .setContent(m.getContent())
                            .setReward(new MixRes(m.getRewardConf()))
                            .setOperation(GDOperation.GM_MAIL_BASE + m.getType())
                            .build();
                    mail.type = Mail.TYPE_GM;
                    roleMail.add(mail);
                    this.exeId = m.getExeId();
                    log.info("GM邮件exeId被设置为{}", this.exeId);
                }
            }
        } catch (Exception e) {
            log.error("", e);
        }
    }

    public void onEnter() {
        scan(this.roleMail.getRole().getGame().mail.gmMail.getGmMailList());
    }
}
